<template>
    <t-layout>
        <t-header>
            <t-space align="center">

                <t-select v-model="selected_config.grade" label="年级">
                    <t-option v-for="grade in available_config.grade" :value="grade">
                        {{ grade }}
                    </t-option>
                </t-select>
                <t-select v-model="selected_config.subject" label="学科">
                    <t-option v-for="subject in available_config.subjects" :value="subject">
                        {{ subject }}
                    </t-option>
                </t-select>
                <t-select v-model="selected_config.class_name" label="班级">
                    <t-option v-for="class_name in available_config.class_names" :value="class_name">
                        {{ class_name }}
                    </t-option>
                </t-select>
            </t-space>
        </t-header>
        <t-content style="margin: auto;">

            <t-alert theme="info" message="请在上方选择年级班级和科目" v-if="showSkeleton" />
            <t-skeleton :loading="showSkeleton">
                <t-alert theme="success" message="今日已复习完！" v-if="noCard" />
                <div class="card" v-else>
                    <t-space direction="vertical" v-if="currentCard" size="medium">
                        <!-- 美化问题区域 -->
                        <p>小提示：同时按下Ctrl+加号可以放大字体，Ctrl+减号可以缩小字体</p>
                        <p>剩余闪卡数量：{{ currentCard.card_count }}</p>
                        <div class="question-container">
                            <div class="question" style="font-size:30px">{{ currentCard.question }}</div>
                            <div class="answer" v-show="showAnswer" style="font-size:30px">{{ currentCard.answer }}
                            </div>
                        </div>

                        <!-- 美化按钮区域 -->
                        <div class="button-group">
                            <t-button v-if="!showAnswer" @click="showAnswer = true" theme="primary" size="large">
                                显示答案
                            </t-button>
                            <t-space v-else class="rating-buttons">
                                <t-button v-for="rating in [1, 2, 3, 4]" :key="rating" @click="submitReview(rating)"
                                    :theme='["danger", "warning", "primary", "success"][rating - 1]' size="large"
                                    shape="round">
                                    {{ ['完全忘记', '困难', '好', '非常简单'][rating - 1] }}
                                </t-button>
                                <t-popconfirm content="确定要删除这张卡片吗？" @onConfirm="deleteCard">
                                    <t-button theme="danger" size="large" shape="round">
                                        删除卡片
                                    </t-button>
                                </t-popconfirm>
                            </t-space>
                        </div>

                        <!-- 美化卡片信息列表 -->
                        <div class="info-card" shadow>
                            <t-list size="small">
                                <t-list-item>
                                    <t-list-item-meta title="创建时间"
                                        :description="convertUtcToLocal(currentCard.create_time)" />
                                </t-list-item>
                                <t-list-item>
                                    <t-list-item-meta title="到期时间" :description="convertUtcToLocal(currentCard.due)" />
                                </t-list-item>
                                <t-list-item>
                                    <t-list-item-meta title="难度" :description="currentCard.fsrs_status.difficulty" />
                                </t-list-item>
                                <t-list-item>
                                    <t-list-item-meta title="回忆概率"
                                        :description="currentCard.fsrs_status.retrievability" />
                                </t-list-item>
                                <t-list-item>
                                    <t-list-item-meta title="记忆稳定性"
                                        :description="currentCard.fsrs_status.stability" />
                                </t-list-item>
                                <t-list-item>
                                    <t-list-item-meta title="学习状态" :description="currentCard.fsrs_status.state" />
                                </t-list-item>
                                <t-list-item>
                                    <t-list-item-meta title="卡id" :description="String(currentCard.id)" />
                                </t-list-item>


                            </t-list>
                        </div>
                    </t-space>
                </div>
            </t-skeleton>
        </t-content>
    </t-layout>
</template>
<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import axios from 'axios'

// 从本地存储加载配置
const loadConfigFromStorage = () => {
  const savedConfig = localStorage.getItem('classicReviewConfig')
  return savedConfig ? JSON.parse(savedConfig) : { grade: '', subject: '', class_name: '' }
}

// 保存配置到本地存储
const saveConfigToStorage = (config) => {
  localStorage.setItem('classicReviewConfig', JSON.stringify(config))
}

const selected_config = ref(loadConfigFromStorage())
//判断是否显示骨架屏
const showSkeleton = computed(() => {
    return !selected_config.value.grade || !selected_config.value.subject || !selected_config.value.class_name;
})
const available_config = ref({ grade: [], subject: [], class_name: [] })
const loadAvailableConfig = async () => {
    try {
        const response = await axios.get('/api/config')
        available_config.value = response.data
    } catch (error) {
        console.error('Error fetching config:', error)
        MessagePlugin.error('获取配置失败，请截图并发送给作者', error)
    }
}
onMounted(() => {
    document.title = '复习闪卡'
    loadAvailableConfig()  
    fetchCard()
})
const currentCard = ref(null)
const showAnswer = ref(false)
const isLoading = ref(false)
const noCard = ref(false)

const fetchCard = async () => {
    if (showSkeleton.value) return

    isLoading.value = true
    try {
        const { grade, subject, class_name } = selected_config.value
        const response = await axios.get('/api/get_card', {
            params: { grade, subject, class_name }
        })
        if (response.status == 204) {
            noCard.value = true
        }
        else if (response.status == 200) {
            noCard.value = false
            currentCard.value = response.data
            console.log('新闪卡', currentCard.value)
            showAnswer.value = false
        }
        else {
            MessagePlugin.error('获取卡片失败，请截图并发送给作者', response.status, response.data)
        }
    } catch (error) {
        if (error.response?.status === 404) {
            currentCard.value = null
        } else {
            console.error('Error fetching card:', error)
        }
    } finally {
        isLoading.value = false
    }
}

const submitReview = async (rating) => {
    if (!currentCard.value) return

    try {
        var response= await axios.post('/api/review', {
            card_id: currentCard.value.id,
            rating: rating
        })
        MessagePlugin.success('复习成功，下次时间：'+convertUtcToLocal(response.data.new_due))
        fetchCard() // 获取下一张卡片
    } catch (error) {
        console.error('反馈学习情况时出现错误，请截图并发送给作者:', error)
    }
}
const deleteCard = async () => {
    if (!currentCard.value) return

    try {
        await axios.delete('/api/delete', {
            data: { id: currentCard.value.id }
        })
        MessagePlugin.success('卡片已删除')
        fetchCard() // 删除后获取下一张卡片
    } catch (error) {
        console.error('Error deleting card:', error)
    }
}
function convertUtcToLocal(utcString) {
    if(!utcString) return '';
    const date = new Date(utcString + 'Z');
    const daysDiff = Math.round((date - new Date())/(1000*60*60*24));
    return `${date.getMonth()+1}月${date.getDate()}日(${Math.abs(daysDiff)}天${daysDiff > 0 ? '后' : '前'})`;
}
// 修改watch监听，保存配置变更
watch(selected_config, (newVal) => {
  if (newVal.grade && newVal.subject && newVal.class_name) {
    fetchCard()
    saveConfigToStorage(newVal)
  }
}, { deep: true })
</script>

<style scoped>
.card {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
}

.question-container {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.question {
    font-size: 18px;
    font-weight: 500;
    margin-bottom: 15px;
    color: #333;
}

.answer {
    font-size: 16px;
    color: #666;
    padding-top: 15px;
    border-top: 1px dashed #e5e5e5;
}

.button-group {
    margin: 20px 0;
    text-align: center;
}

.rating-buttons {
    justify-content: center;
    gap: 12px;
}

.info-card {
    margin-top: 20px;
    border-radius: 8px;
}

.no-card {
    text-align: center;
    padding: 40px 0;
}
</style>
